#include <stdio.h>
#include <stdlib.h>

#define maxSize 6

typedef struct doubleLinkedList
{
    // 前驱指针
    struct doubleLinkedList* prior;
    int data;
    //后继指针
    struct doubleLinkedList* next;
}doubleLinkedList;

//双链表的创建函数
doubleLinkedList* initDoubleLinkedList(doubleLinkedList * head);

//输出双链表的函数
void displayDoubleLinkedList(doubleLinkedList* head);

int main(int argc, char* argv[]) {
    //创建一个头指针
    doubleLinkedList * head = NULL;
    //调用链表创建函数
    head = initDoubleLinkedList(head);
    //输出创建好的链表
    displayDoubleLinkedList(head);

    //显示双链表的优点
    printf("链表中第 4 个节点的直接前驱是：%d", head->next->next->next->prior->data);
}

//双链表的创建函数
doubleLinkedList* initDoubleLinkedList(doubleLinkedList * head) {
    //创建一个首元节点，链表的头指针为head
    head = (doubleLinkedList *)malloc(sizeof(doubleLinkedList));
    head->prior = NULL;
    head->next = NULL;
    head->data = 1;

    //声明一个指向首元节点的指针，方便后期向链表中添加新创建的节点
    doubleLinkedList * tempHead = head;
    for(int i=2; i<maxSize; i++) {
        doubleLinkedList * list = (doubleLinkedList *)malloc(sizeof(doubleLinkedList));
        //新节点与链表最后一个节点建立关系
        list->prior = tempHead;
        list->next = NULL;
        list->data = i;
        //链表中最后一个节点tempHead指向新节点list
        tempHead->next = list;
        //tempHead永远指向链表中最后一个节点
        tempHead = tempHead->next;
    }
    //返回新创建的链表
    return head;
}

//输出双链表的函数
void displayDoubleLinkedList(doubleLinkedList* head) {
    //声明一个指向首元节点的指针
    doubleLinkedList * tempHead = head;
    while(tempHead) {
        if(tempHead->next) {
            printf("%d <-> ", tempHead->data);
        } else {
            printf("%d\n", tempHead->data);
        }
        tempHead = tempHead->next;
    }
    
}
